package com.leoman.work.controller;

import com.leoman.adsindex.entity.AdsIndex;
import com.leoman.adsindex.service.AdsIndexService;
import com.leoman.banner.entity.Banner;
import com.leoman.banner.service.BannerService;
import com.leoman.barrage.entity.Barrage;
import com.leoman.barrage.service.BarrageService;
import com.leoman.category.entity.Category;
import com.leoman.category.service.CategoryService;
import com.leoman.comment.service.WorkCommentService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.floatwin.entity.FloatWin;
import com.leoman.floatwin.service.FloatWinService;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.service.UserService;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import com.leoman.work.entity.*;
import com.leoman.work.service.*;
import com.leoman.work.service.impl.WorkServiceImpl;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/15 0015.
 */
@Controller
@RequestMapping(value = "admin/comic")
public class ComicController extends GenericEntityController<Work, Work, WorkServiceImpl> {

    @Autowired
    private WorkService workService;

    @Autowired
    private WorkComicService workComicService;

    @Autowired
    private UserService userService;

    @Autowired
    private WorkSurroundService workSurroundService;

    @Autowired
    private WorkCreatorService workCreatorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WorkComicImageService workComicImageService;

    @Autowired
    private WorkCommentService workCommentService;

    @Autowired
    private BarrageService barrageService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    @Autowired
    private BannerService bannerService;

    @Autowired
    private AdsIndexService adsIndexService;

    @Autowired
    private FloatWinService floatWinService;

    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "comic/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String name,
                     Long typeList,
                     Integer status,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {
            List<WorkComic> workComicList;
            int pageNum = getPageNum(start, length);

            Page<Work> page = workService.page(name, typeList, status, Constant.CATEGORY_TYPE_006, pageNum, length);
            //List<Barrage> barrageList = null;
            for (Work work : page.getContent()) {
                if (StringUtils.isNotEmpty(work.getCover())) {
                    work.setCover(ImageUtil.clearUploadUrl(work.getCover()));
                }

                // 查询最新漫画话集
                workComicList = workComicService.findByWorkId(work.getId());
                if (workComicList.size() != 0) {
                    work.setWorkComic(workComicList.get(workComicList.size() - 1));
                }

                /*for (WorkComic workComic : workComicList) {
                    barrageList = barrageService.findByTypeAndWorkId(workComic.getId(), 1);
                    work.setBarrageNum(work.getBarrageNum() + (barrageList != null? barrageList.size() : 1));
                }*/
            }
            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 话集列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexComic")
    public String indexComic(Long workId, Model model) {

        List<WorkComic> workComicList;
        Work work = workService.queryByPK(workId);

        // 查询最新漫画话集
        workComicList = workComicService.findByWorkId(work.getId());
        if (workComicList.size() != 0) {
            work.setWorkComic(workComicList.get(workComicList.size() - 1));
        }

        model.addAttribute("work", work);

        return "comic/comicList";
    }

    /**
     * 查询话集列表
     */
    @RequestMapping(value = "/comicList")
    public void comicList(HttpServletResponse response,
                          Long workId,
                          Integer draw,
                          Integer start,
                          Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<WorkComic> page = workComicService.page(workId, pageNum, length);

            List<WorkComic> workComicList = page.getContent();
            List<WorkComicImage> workComicImageList;
            List<Barrage> barrageList = null;
            for (WorkComic workComic : workComicList) {

                // 查询漫画图片数量
                workComicImageList = workComicImageService.findByComicId(workComic.getId());
                workComic.setImageList(workComicImageList.size());

                barrageList = barrageService.findByTypeAndWorkId(workComic.getId(), 1);
                workComic.setBarrageNum(barrageList != null ? barrageList.size() : 1);
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 更新下一话
     *
     * @return path
     */
    @RequestMapping(value = "/update")
    public String update(Model model, Long workId, Integer series) {

        Work work = workService.queryByPK(workId);

        model.addAttribute("work", work);
        model.addAttribute("series", series + 1);
        model.addAttribute("workComicImageList", JSONArray.fromObject(null));

        return "comic/update";
    }

    /**
     * 编辑下一话
     *
     * @return path
     */
    @RequestMapping(value = "/updateEdit")
    public String updateEdit(Model model, Long comicId) {

        Map<String, Object> map;
        List<Map<String, Object>> list = new ArrayList<>();

        WorkComic workComic = workComicService.queryByPK(comicId);
        Work work = workComic.getWork();
        Integer series = workComic.getSeries();

        List<WorkComicImage> workComicImageList = workComicImageService.findByComicId(workComic.getId());
        for (WorkComicImage workComicImage : workComicImageList) {
            map = new HashMap<>();
            map.put("id", workComicImage.getId());
            map.put("path", ImageUtil.clearUploadUrl(workComicImage.getUrl()));

            list.add(map);
        }

        model.addAttribute("workComic", workComic);
        model.addAttribute("work", work);
        model.addAttribute("series", series);
        model.addAttribute("workComicImageList", JSONArray.fromObject(list));

        return "comic/update";
    }

    /**
     * 上传缓存图片
     */
    @RequestMapping("/addTempImage")
    @ResponseBody
    public WorkComicImage addTempImage(MultipartRequest multipartRequest) {
        WorkComicImage image = new WorkComicImage();

        try {
            MultipartFile multipartFile = multipartRequest.getFile("tempImage");

            // 验证图片格式
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return image;
            }

            FileBo fileBo = FileUtil.save(multipartFile, true);
            image.setUrl(fileBo.getPath());
            image.setSuolue(fileBo.getSuoluePath());

            workComicImageService.save(image);
            image.setUrl(ImageUtil.clearUploadUrl(fileBo.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return image;
    }

    /**
     * 保存更新下一话
     */
    @RequestMapping(value = "/updateSave")
    @ResponseBody
    public Integer updateSave(Long workId,
                              Long workComicId,
                              String comic,
                              Integer series,
                              Integer status,
                              String tempAddImageIds1,
                              String tempDelImageIds) throws UnsupportedEncodingException {

        String[] addImageIds1 = tempAddImageIds1.split(",");
        String[] delImageIds = tempDelImageIds.split(",");

        comic = sensitiveWordsService.replaceWord(comic);
        WorkComic workComic;
        if (workComicId == null) {
            workComic = new WorkComic();
            workComic.setCreateDate(System.currentTimeMillis());
            workComic.setPlayNum(0);
            workComic.setBarrageNum(0);
        } else {
            workComic = workComicService.queryByPK(workComicId);
            workComic.setUpdateDate(System.currentTimeMillis());
        }

        Work work = workService.queryByPK(workId);
        if (status == null) {
            work.setIsEnd(0);
        } else {
            work.setIsEnd(status);
        }
        workService.update(work);

        workComic.setSeries(series);
        workComic.setWork(work);
        if (comic.equals("")) {
            workComic.setName("第" + series + "章");
        } else {
            workComic.setName(comic);
        }
        List<WorkCreator> tempList = workCreatorService.findWorkId(workComic.getWork().getId());
        if (null != tempList && tempList.size() > 0) {
            workComic.setAuthor(tempList.get(0).getUserInfo().getNickname());
        }
        workComic.setUpdateDate(System.currentTimeMillis());
        workComicService.update(workComic);

        // 保存漫画图片集合
        WorkComicImage image;
        for (String imageId : addImageIds1) {
            if (null != imageId && !imageId.equals("")) {
                image = workComicImageService.queryByPK(Long.parseLong(imageId));
                image.setWorkComic(workComic);

                workComicImageService.update(image);
            }
        }

        List<WorkComicImage> workComicImageList = workComicImageService.findByComicId(workComic.getId());
        // 删除漫画图片集合
        WorkComicImage image2;
        List<Barrage> barrageList = null;
        for (String imageId : delImageIds) {
            if (null != imageId && !imageId.equals("")) {

                // 查询该漫画图片的弹幕列表
                for (int i = 0; i < workComicImageList.size(); i++) {
                    if (workComicImageList.get(i).getId() == Long.parseLong(imageId)) {
                        barrageList = barrageService.findByWorkIdAndTimePlus(workComic.getId(), i);
                    }
                }
                // 删除该漫画图片的弹幕
                if (barrageList != null) {
                    for (Barrage barrage : barrageList) {
                        barrageService.deleteBarrage(barrage.getId());
                    }
                }

                image2 = workComicImageService.queryByPK(Long.parseLong(imageId));
                workComicImageService.delete(image2);
            }
        }

        return 1;
    }

    /**
     * 查询主创列表
     */
    @RequestMapping(value = "/creatorList")
    @ResponseBody
    public List<UserInfo> creatorList() {

        return userService.findByStatus();
    }

    /**
     * 查询类型列表
     */
    @RequestMapping(value = "/typeList")
    @ResponseBody
    public List<Category> typeList() {

        return categoryService.findType(Constant.CATEGORY_TYPE_006);
    }


    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    public String add(Model model) {

        List<UserInfo> creatorList = userService.findByStatus();
        model.addAttribute("creatorList", creatorList);

        return "comic/add";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit")
    public String edit(Long workId, Model model) {
        try {
            //Map<String, Object> map = new HashMap<String, Object>();
            //List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            Work work = workService.queryByPK(workId);
            if (StringUtils.isNotEmpty(work.getCover())) {
                work.setCover(ImageUtil.clearUploadUrl(work.getCover()));
            }

            List<WorkCreator> workCreatorList = workCreatorService.findWorkId(workId);

            List<WorkSurround> workSurroundList = workSurroundService.findByWorkId(workId);

            model.addAttribute("work", work);
            model.addAttribute("workCreatorList", workCreatorList);
            model.addAttribute("workSurroundList", workSurroundList);

            StringBuilder sb = new StringBuilder("");
            for (WorkCreator workCreator : workCreatorList) {
                sb.append(workCreator.getUserInfo().getId() + ",");
            }

            model.addAttribute("tempCreatorIds", sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "comic/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(Long id,
                        String name,
                        Integer seriesCount,
                        Long category,
                        String description,
                        String[] creator,
                        String[] type,
                        String[] welfareList,
                        String[] types,
                        String[] welfareLists,
                        MultipartRequest multipartRequest) throws IOException {

        // 过滤敏感字符
        name = sensitiveWordsService.replaceWord(name);
        description = sensitiveWordsService.replaceWord(description);

        workSurroundService.saveAll(id, name, seriesCount, category, description, creator, type, welfareList,
                types, welfareLists, multipartRequest);

        return 1;
    }

    /**
     * 删除漫画话集
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    private Integer delete(Long comicId) {

        /*WorkComic workComic = workComicService.queryByPK(comicId);
        workComic.setStatus(1);
        workComicService.update(workComic);

        // 查询漫画话集评论
        List<WorkComment> workCommentList = workCommentService.findList(workComic.getId(), Constant.CATEGORY_TYPE_006, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_YES);
        for (WorkComment workComment : workCommentList) {
            workCommentService.deleteComment(workComment.getId());
        }

        // 查询漫画话集的弹幕
        List<Barrage> barrageList = barrageService.findByTypeAndWorkId(workComic.getId(), 0);
        for (Barrage barrage : barrageList) {
            barrageService.delete(barrage);
        }*/


        return workComicService.deleteComic(comicId);
    }

    /**
     * 预览
     */
    @RequestMapping(value = "/detail")
    private String detail(Model model, Long comicId) {

        WorkComic workComic = workComicService.queryByPK(comicId);

        //Map<String, Object> map = new HashMap<String, Object>();
        //List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        List<WorkComicImage> workComicImageList = workComicImageService.findByComicId(workComic.getId());
        workComic.setImageList(workComicImageList.size());
        for (WorkComicImage workComicImage : workComicImageList) {
            if (StringUtils.isNotEmpty(workComicImage.getUrl())) {
                workComicImage.setUrl(ImageUtil.clearUploadUrl(workComicImage.getUrl()));
            }
        }

        model.addAttribute("workComic", workComic);
        model.addAttribute("workComicImageList", workComicImageList);
        //model.addAttribute("workComicImageList", JSONArray.fromObject(list));

        return "comic/detail";
    }

    /**
     * 批量删除漫画
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @ResponseBody
    public Integer deleteBatch(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        List<WorkComment> workCommentList;
        List<Barrage> barrageList;
        for (Long id : arrayId) {

            // 是否链接到广告banner
            List<Banner> bannerList = bannerService.findByTypeAndCategoryId(Constant.POSITION_003, id);
            if (bannerList.size() != 0) {
                return 2;
            }

            // 是否链接到首页推荐
            List<AdsIndex> adsIndexList = adsIndexService.findByTypeAndCategoryId(Constant.POSITION_003, id);
            if (adsIndexList.size() != 0) {
                return 2;
            }

            // 是否链接到浮窗广告
            List<FloatWin> floatWinList = floatWinService.findByTypeAndCategoryId(Constant.POSITION_003, id);
            if (floatWinList.size() != 0) {
                return 2;
            }

            // 删除该视频的周边购买
            List<WorkSurround> workSurroundList = workSurroundService.findByWorkId(id);
            for (WorkSurround workSurround : workSurroundList) {
                workSurroundService.delete(workSurround);
            }

            List<WorkComic> workComicList = workComicService.findByWorkId(id);
            for (WorkComic workComic : workComicList) {
                // 查询漫画话集评论
                workCommentList = workCommentService.findList(workComic.getId(), Constant.CATEGORY_TYPE_006, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_YES);
                for (WorkComment workComment : workCommentList) {
                    workCommentService.delete(workComment);
                }

                // 查询漫画话集弹幕
                barrageList = barrageService.findByTypeAndWorkId(workComic.getId(), 0);
                for (Barrage barrage : barrageList) {
                    barrageService.delete(barrage);
                }
            }

            // 查询漫画评论
            workCommentList = workCommentService.findList(id, Constant.CATEGORY_TYPE_006, Constant.COMMENT_TYPE_DEFAULT, Constant.COMMENT_PRAISE_ISDETAIL_NO);
            for (WorkComment workComment : workCommentList) {
                workCommentService.delete(workComment);
            }
            workService.deleteWork(id);

        }
        return 1;
    }

    /**
     * 批量删除漫画话集
     */
    @RequestMapping(value = "/deleteBatchComic", method = RequestMethod.POST)
    @ResponseBody
    public Integer deleteBatchComic(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        for (Long id : arrayId) {
            workComicService.deleteComic(id);
        }
        return 1;
    }

    /**
     * 查询漫画主创列表
     */
    @RequestMapping(value = "/comicCreatorList")
    @ResponseBody
    public List<UserInfo> comicCreatorList(Long workId) {

        List<WorkCreator> videoCreatorList = workCreatorService.findWorkId(workId);
        List<UserInfo> creatorList = new ArrayList<>();
        for (WorkCreator workCreator : videoCreatorList) {
            creatorList.add(workCreator.getUserInfo());
        }
        return creatorList;
    }

    /**
     * 新增主创弹幕
     */
    @RequestMapping(value = "/addBarrage")
    @ResponseBody
    public Integer addBarrage(Integer timePlus,
                              String detail,
                              Long barrageId,
                              Long workComicId,
                              Long creatorId) throws UnsupportedEncodingException {


        Barrage barrage;
        if (barrageId == null) {
            barrage = new Barrage();
        } else {
            barrage = barrageService.queryByPK(barrageId);
        }

        //barrage.setUserLogin(userService.queryByPK(creatorId).getUserLogin());
        barrage.setUserInfo(userService.queryByPK(creatorId));
        detail = sensitiveWordsService.replaceWord(detail);

        WorkComic workComic = workComicService.queryByPK(workComicId);
        barrage.setContent(detail);
        barrage.setType(1);
        barrage.setTimePlus(timePlus);
        barrage.setTime(workComic.getSeries());
        barrage.setWorkId(workComicId);
        barrage.setPraise(0L);
        barrage.setName(workComicService.queryByPK(workComicId).getWork().getName());
        barrageService.save(barrage);

        // 增加漫画话集弹幕数
        //WorkComic workComic = workComicService.queryByPK(workComicId);
        workComic.setBarrageNum(workComic.getBarrageNum() + 1);
        workComicService.save(workComic);

        // 增加漫画总弹幕数
        Work work = workComicService.queryByPK(workComicId).getWork();
        work.setBarrageNum(work.getBarrageNum() + 1);
        workService.update(work);
        return 1;

    }

    /**
     * 主创弹幕列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexBarrage")
    public String indexBarrage(Long workId, Model model) {

        WorkComic workComic = workComicService.queryByPK(workId);
        //WorkCreator workCreator = workCreatorService.findByWorkId(workVideo.getWork().getId());
        // 查询漫画图片数
        List<WorkComicImage> workComicImageList = workComicImageService.findByComicId(workId);
        workComic.setImageList(workComicImageList != null ? workComicImageList.size() : 0);

        model.addAttribute("workComic", workComic);
        //model.addAttribute("workCreator", workCreator);

        return "comic/barrageList";
    }

    /**
     * 查询弹幕列表
     */
    @RequestMapping(value = "/barrageList")
    public void barrageList(HttpServletResponse response,
                            Long workId,
                            Integer draw,
                            Integer start,
                            Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<Barrage> page = barrageService.page(workId, pageNum, length);

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }
}
